package com.ruoyi.shop.service.impl;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.shop.domain.ShopCoupon;
import com.ruoyi.shop.service.IShopCouponService;
import com.ruoyi.shop.util.GenNumberUtils;
import com.ruoyi.shop.util.NsDateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.shop.mapper.ShopCouponCodeMapper;
import com.ruoyi.shop.domain.ShopCouponCode;
import com.ruoyi.shop.service.IShopCouponCodeService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 优惠券领取记录Service业务层处理
 * 
 * @author Alan Zhang
 * @date 2021-09-14
 */
@Service
public class ShopCouponCodeServiceImpl implements IShopCouponCodeService 
{
    @Autowired
    private ShopCouponCodeMapper shopCouponCodeMapper;
    @Autowired
    private IShopCouponService shopCouponService;
    /**
     * 查询优惠券领取记录
     * 
     * @param id 优惠券领取记录主键
     * @return 优惠券领取记录
     */
    @Override
    public ShopCouponCode selectShopCouponCodeById(Long id)
    {
        return shopCouponCodeMapper.selectShopCouponCodeById(id);
    }

    /**
     * 查询优惠券领取记录列表
     * 
     * @param shopCouponCode 优惠券领取记录
     * @return 优惠券领取记录
     */
    @Override
    public List<ShopCouponCode> selectShopCouponCodeList(ShopCouponCode shopCouponCode)
    {
        return shopCouponCodeMapper.selectShopCouponCodeList(shopCouponCode);
    }

    /**
     * 新增优惠券领取记录
     * 
     * @param shopCouponCode 优惠券领取记录
     * @return 结果
     */
    @Override
    public int insertShopCouponCode(ShopCouponCode shopCouponCode)
    {
        shopCouponCode.setCreateTime(DateUtils.getNowDate());
        return shopCouponCodeMapper.insertShopCouponCode(shopCouponCode);
    }

    /**
     * 修改优惠券领取记录
     * 
     * @param shopCouponCode 优惠券领取记录
     * @return 结果
     */
    @Override
    public int updateShopCouponCode(ShopCouponCode shopCouponCode)
    {
        return shopCouponCodeMapper.updateShopCouponCode(shopCouponCode);
    }

    /**
     * 批量删除优惠券领取记录
     * 
     * @param ids 需要删除的优惠券领取记录主键
     * @return 结果
     */
    @Override
    public int deleteShopCouponCodeByIds(String ids)
    {
        return shopCouponCodeMapper.deleteShopCouponCodeByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除优惠券领取记录信息
     * 
     * @param id 优惠券领取记录主键
     * @return 结果
     */
    @Override
    public int deleteShopCouponCodeById(Long id)
    {
        return shopCouponCodeMapper.deleteShopCouponCodeById(id);
    }

    /**
     * 校验优惠券
     * @param couponCode
     * @param orderTotalAmount
     * @param usedUserId
     * @return
     */
    @Override
    public boolean valid(ShopCouponCode couponCode, BigDecimal orderTotalAmount, long usedUserId) {

        // 该优惠码被标识为：不可用
        if (couponCode == null || !couponCode.isNormal()) {
            throw new BusinessException("该优惠码不存在或已失效");
        }

        ShopCoupon coupon = shopCouponService.selectShopCouponById(couponCode.getCouponId());

        couponCode.setShopCoupon(coupon);//绑定一个优惠券对象，否则选择优惠券无法展示前端无法展示

        // 该优惠券不可用
        if (coupon == null || !coupon.isNormal()) {
            throw new BusinessException("该优惠码不存在或已失效");
        }

        //是否是只有优惠券拥有者可用
        if ( !couponCode.getUserId().equals(usedUserId)) {
            throw new BusinessException("该优惠码只能自己使用");
        }

        Integer couponType = coupon.getType();
        //满减券
        if (couponType != null && couponType == ShopCoupon.TYPE_FULL_DISCOUNT) {
            BigDecimal withAmount = coupon.getWithAmount();
            if (withAmount == null || withAmount.compareTo(BigDecimal.ZERO) < 0) {
                throw new BusinessException("该优惠券配置错误，请联系管理员");
            }
            if (orderTotalAmount.compareTo(coupon.getWithAmount()) < 0) {
                throw new BusinessException("订单总价格必须购买超过 " + new DecimalFormat("0.00").format(coupon.getWithAmount()) + " 元才能使用该优惠码。");
            }
        }

        Date validTime = couponCode.getValidTime();
        int validtype = coupon.getValidType();

        //绝对时间内有效
        if (validtype == ShopCoupon.VALID_TYPE_ABSOLUTELY_EFFECTIVE) {
            boolean timeValide = validTime.getTime() > coupon.getValidStartTime().getTime()
                    && validTime.getTime() < coupon.getValidEndTime().getTime();

            if (!timeValide) {
                throw new BusinessException("该优惠码已经过期");
            }
        }
        //相对时间内有效
        else if (validtype == ShopCoupon.VALID_TYPE_RELATIVELY_EFFECTIVE) {
            boolean timeValide = System.currentTimeMillis() < DateUtils.addDays(validTime, coupon.getValidDays()).getTime();
            if (!timeValide) {
                throw new BusinessException("该优惠码已经过期");
            }
        }

        return true;
    }

    /**
     * 根据code 获取优惠券
     * @param couponCode
     * @return
     */
    @Override
    public ShopCouponCode findByCode(String couponCode){
        return shopCouponCodeMapper.findByCode(couponCode);
    }


    /**
     * 使用记录数量
     * @param couponId
     * @return
     */
    @Override
    public Long queryCountByCouponId(Long couponId) {
        return shopCouponCodeMapper.queryCountByCouponId(couponId);
    }

    /**
     * 优惠券领取
     * @param couponId 优惠券ID
     * @param userId  用户ID
     */
    @Transactional
    @Override
    public AjaxResult drawCoupon(Long couponId, Long userId) {
        ShopCoupon shopCoupon = shopCouponService.selectShopCouponById(couponId);
        if(!shopCoupon.isNormal()){
            return AjaxResult.error("不能领取");
        }

        if(shopCoupon.getQuota() <= 0){
            return AjaxResult.error("手慢，领取完了");
        }

        Date validTime;
        if(shopCoupon.getValidType() == ShopCoupon.VALID_TYPE_ABSOLUTELY_EFFECTIVE){
            validTime = shopCoupon.getValidEndTime();
        } else if(shopCoupon.getValidType() == ShopCoupon.VALID_TYPE_RELATIVELY_EFFECTIVE){
            validTime = NsDateUtils.addDateDays(shopCoupon.getValidDays());
        } else {
            return AjaxResult.error("领取失败");
        }
        ShopCouponCode shopCouponCode = new ShopCouponCode();
        shopCouponCode.setTitle(shopCoupon.getTitle());
        shopCouponCode.setType(shopCoupon.getType());
        shopCouponCode.setWithAmount(shopCoupon.getWithAmount());
        shopCouponCode.setAmount(shopCoupon.getAmount());
        shopCouponCode.setValidTime(validTime);
        shopCouponCode.setCouponId(couponId);
        shopCouponCode.setCode(GenNumberUtils.uuid());
        shopCouponCode.setStatus(ShopCouponCode.STATUS_NORMAL);
        shopCouponCode.setUserId(userId);
        int rows = insertShopCouponCode(shopCouponCode);
        if(rows > 0) {

            shopCoupon.setQuota(shopCoupon.getQuota() - 1);

            shopCouponService.updateShopCoupon(shopCoupon);

            shopCouponService.doSyncTakeCount(shopCoupon.getId());
        }
        return AjaxResult.success();
    }
}
